﻿using System;
using System.Collections.Concurrent;
using System.Collections;

namespace RAP.Framework.Libary.ServerCacheManager.CacheProxy
{
  /// <summary>
  /// 内存缓存对象
  /// </summary>
  public class MemoryCachedObject : CacheObjectBase, IDictionary
  {
    protected IDictionary _cachedObject = new ConcurrentDictionary<string, object>();

    public MemoryCachedObject(string name)
  : base(name)
    {
    }

    public virtual void Add(object key, object value)
    {
      _cachedObject[key] = value;
      this.fireCacheAddedEvent(key, value);
    }

    public virtual void Clear()
    {
      _cachedObject.Clear();
      this.fireCacheClearedEvent();
    }

    public virtual bool Contains(object key)
    {
      return _cachedObject.Contains(key);
    }

    public virtual IDictionaryEnumerator GetEnumerator()
    {
      return _cachedObject.GetEnumerator();
    }

    public virtual bool IsFixedSize
    {
      get { return _cachedObject.IsFixedSize; }
    }

    public virtual bool IsReadOnly
    {
      get { return _cachedObject.IsReadOnly; }
    }

    public virtual ICollection Keys
    {
      get { return _cachedObject.Keys; }
    }

    public virtual void Remove(object key)
    {
      if (_cachedObject.Contains(key))
      {
        object value = _cachedObject[key];
        _cachedObject.Remove(key);
        this.fireCacheRemovedEvent(key, value);
      }
    }

    public virtual ICollection Values
    {
      get { return _cachedObject.Values; }
    }

    public virtual object this[object key]
    {
      get
      {
        return _cachedObject[key];
      }
      set
      {
        _cachedObject[key] = value;
        if (value != null)
        {
          this.fireCacheAddedEvent(key, value);
        }
        else
        {
          this.fireCacheRemovedEvent(key, value);
        }
      }
    }

    public virtual void CopyTo(Array array, int index)
    {
      _cachedObject.CopyTo(array, index);
    }

    public virtual int Count
    {
      get { return _cachedObject.Count; }
    }

    public virtual bool IsSynchronized
    {
      get { return _cachedObject.IsSynchronized; }
    }

    public virtual object SyncRoot
    {
      get { return _cachedObject.SyncRoot; }
    }

    protected virtual IEnumerator _getEnumerator()
    {
      return _cachedObject.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
      return _getEnumerator();
    }

  }
}
